package org.scboy.common.request.inter;

import java.util.Map;
import java.util.Objects;

import org.scboy.common.cache.InterLangCache;
import org.scboy.utils.caches.dbms.entity.InterEntity;
import org.scboy.utils.entitys.coobi.Model;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import jakarta.servlet.http.HttpServletRequest;

/**
 * 国际化
 * @author yanghao
 *
 */
public class Inter {
	
	/**
	 * 获取国际化提示信息
	 * @param request request请求
	 * @param code 返回逻辑编码
	 * @return
	 */
	public static String msg(String code){
		RequestAttributes ra=RequestContextHolder.getRequestAttributes();
		String lang="zh_CN";
		if(!Objects.isNull(ra)) {
			ServletRequestAttributes sra=(ServletRequestAttributes)ra;
			HttpServletRequest request = sra.getRequest();
			lang=(String) request.getHeader("Bmps-Inter-Language");
		}
		return getMsg(lang, code);
	}
	
	/**
	 * 获取消息返回
	 * 默认提示信息找不到将返回代码。
	 * @param language 语言类别
	 * @param code 返回编码
	 * @return
	 */
	public static String getMsg(String lang,String code){
		
		if(StrUtil.isEmpty(code)) {
			return "";
		}

		InterLangCache cache=SpringUtil.getBean(InterLangCache.class);
		
		InterEntity inter= cache.get(code, lang);
		
		if(inter==null) {
			return code;
		}else {
			return inter.getMsg();
		}
	}
	
	/**
	 * 获取国际化提示信息，并提示。
	 * @param request request请求
	 * @param code 返回逻辑编码
	 * @param params 格式化参数
	 * @return
	 */
	public static String msg(String code,Model params){
		String msg=msg(code);
		return format(msg, params);
	}
	
	public static String format(CharSequence template, Map<?, ?> map) {
		if (null == template) {
			return null;
		}
		if ((null == map) || (map.isEmpty())) {
			return template.toString();
		}

		String template2 = template.toString();
		for (Map.Entry<?, ?> entry : map.entrySet()) {
			String msgValue=Convert.toStr(entry.getValue(),"");
			template2 = template2.replace("{" + entry.getKey() + "}",
					StrUtil.utf8Str(msgValue));
		}
		return template2;
	}
}
